package cate.game.pvp.championrace.data;

import cate.common.util.GameResult;
import cate.game.framework.common.compress.CompressedContent;
import cate.game.framework.common.compress.PlaySideCompressHelper;
import cate.game.play.part.PlaySide;
import com.google.common.collect.Lists;
import lombok.Data;
import lombok.ToString;
import org.springframework.data.annotation.Id;

import java.io.IOException;
import java.util.LinkedList;

@ToString
@Data
public class ChampionRacePs {
    @Id
    private String uid;
    private ChampionRaceOpponent opponent;

    private LinkedList<CompressedContent> cpsList;

    public static ChampionRacePs compress(PlaySide ps, long points) throws IOException {
        ChampionRacePs eps = new ChampionRacePs();
        eps.setUid(ps.snapshot.uid);
        eps.setOpponent(ChampionRaceOpponent.ofCopy(ps.snapshot, points));
        LinkedList<CompressedContent> cpsList = Lists.newLinkedList();
        cpsList.add(PlaySideCompressHelper.compress(ps));
        eps.setCpsList(cpsList);
        return eps;
    }

    public static GameResult<ChampionRacePs> compressEc(PlaySide playSide, long points) {
        GameResult<ChampionRacePs> r = new GameResult<>();
        try {
            r.data = compress(playSide, points);
        } catch (Throwable cause) {
            return r.fail(cause);
        }
        return r.success();
    }

    public static ChampionRacePs of(PlaySide ps, long points, int rank) {
        ChampionRacePs eps;
        GameResult<ChampionRacePs> compressRes = compressEc(ps, points);
        if (compressRes.ok()) {
            eps = compressRes.data;
            eps.getOpponent().setPrRank(rank);
        } else {
            eps = new ChampionRacePs();
            eps.setUid(ps.snapshot.uid);
            eps.setOpponent(ChampionRaceOpponent.of(ps.snapshot, points, rank));
            eps.setCpsList(Lists.newLinkedList());
            try{
                eps.getCpsList().add(PlaySideCompressHelper.compress(ps));
            }catch (Exception e) {

            }
        }
        return eps;
    }
}
